package org.example.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.example.common.R;
import org.example.dto.DishDto;
import org.example.dto.SetmealDto;
import org.example.entity.Category;
import org.example.entity.Dish;
import org.example.entity.DishFlavor;
import org.example.service.CategroyService;
import org.example.service.DishFlavorService;
import org.example.service.DishService;
import org.example.service.impl.DishServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/dish")
public class DishContraller {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategroyService categroyService;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 获取菜品列表
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){



        Page<Dish> pageInfo=new Page<>(page,pageSize);
        LambdaQueryWrapper<Dish> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(name),Dish::getName,name);
        queryWrapper.orderByAsc(Dish::getUpdateTime);
        dishService.page(pageInfo,queryWrapper);

        //忽略拷贝records
        Page<DishDto> dishDtoPage=new Page<>();
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");

        List<DishDto> dishDtos=new LinkedList<>();
        for(Dish it:pageInfo.getRecords()){
            DishDto dishDto=new DishDto();
            BeanUtils.copyProperties(it,dishDto);
            Long id = it.getCategoryId();
            Category category = categroyService.getById(id);
            String categoryName = category.getName();
            dishDto.setCategoryName(categoryName);
            dishDtos.add(dishDto);
        }
        dishDtoPage.setRecords(dishDtos);

        return R.success(dishDtoPage);
    }


    /**
     * 保存数据
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody  DishDto dishDto){
        dishService.saveWithFlavor(dishDto);
        String key="dish"+dishDto.getCategoryId()+"_1";
        //清理缓存
        redisTemplate.delete(key);
        return R.success("新增菜品成功");
    }

    /**
     * 修改菜品信息
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> getId(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);

        return R.success(dishDto);
    }

    /**
     * 修改菜品信息
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody  DishDto dishDto){
        dishService.updateWithFlavor(dishDto);
        String key="dish"+dishDto.getCategoryId()+"_1";
        //清理缓存
        redisTemplate.delete(key);
        return R.success("修改成功");
    }

    /**
     * 展示套餐
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        List<DishDto> dishDtos=null;
        String key="dish"+dish.getCategoryId()+"_"+dish.getStatus();
        //首先查询redis查看是否存在缓存
        dishDtos = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if(dishDtos!=null){
            return R.success(dishDtos);
        }

        Long dishId = dish.getCategoryId();
        LambdaQueryWrapper<Dish> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(dishId!=null,Dish::getCategoryId,dishId);
        queryWrapper.eq(Dish::getStatus,1);
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> dishList = dishService.list(queryWrapper);


        dishDtos = dishList.stream().map((item)->{
            DishDto dishDto=new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            Long id = item.getId();
            //查询对应口味信息
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper=new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId,id);
            List<DishFlavor> dishFlavors = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(dishFlavors);
            return dishDto;
        }).collect(Collectors.toList());

        redisTemplate.opsForValue().set(key,dishDtos,60, TimeUnit.MINUTES);
        return R.success(dishDtos);
    }

    /**
     * 停售菜品
     * @param ids
     * @return
     */
    @PostMapping("/status/0")
    public R<String> updateStatusToZero(@RequestParam List<Long> ids){
        LambdaUpdateWrapper<Dish> updateWrapper=new LambdaUpdateWrapper<>();
        updateWrapper.in(Dish::getId,ids).set(Dish::getStatus,0);
        dishService.update(updateWrapper);
        return R.success("停售成功");
    }

    @PostMapping("/status/1")
    public R<String> updateStatusToOne(@RequestParam List<Long> ids){
        LambdaUpdateWrapper<Dish> updateWrapper=new LambdaUpdateWrapper<>();
        updateWrapper.in(Dish::getId,ids).set(Dish::getStatus,1);
        dishService.update(updateWrapper);
        return R.success("启售成功");
    }


    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids){
        LambdaQueryWrapper<Dish> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.in(Dish::getId,ids);
        dishService.remove(queryWrapper);
        return R.success("删除成功");
    }
}
